library ieee;
use ieee.std_logic_1164.all;
use work.mis_componentes.all;


entity alu is
port(cin:std_logic;
	 a:in std_logic_vector(3 downto 0);
	 b:in std_logic_vector(3 downto 0);
	 m:std_logic;
	 s:in std_logic_vector(1 downto 0);
	 Cin:in std_logic;
	 Cout:out std_logic;
	 r:out std_logic_vector(3 downto 0)  );
end alu;

architecture bhv of alu is

signal temp:std_logic_vector(3 downto 0);
signal apb:std_logic_vector(3 downto 0);
signal apbcout:std_logic;

signal bc2:std_logic_vector(3 downto 0);
signal amb:std_logic_vector(3 downto 0);
signal ambcout:std_logic;

signal ac2:std_logic_vector(3 downto 0);
signal bma:std_logic_vector(3 downto 0);
signal bmacout:std_logic;

begin

U1: sum4bits PORT MAP(a,b,apb,apbcout);

U2: complemento2 PORT MAP(b(0),b(1),b(2),b(3),bc2);
U3: sum4bits PORT MAP(a,bc2,amb,ambcout);


U4: complemento2 PORT MAP(a(0),a(1),a(2),a(3),ac2);
U5: sum4bits PORT MAP(b,ac2,bma,bmacout);


process(m,temp,apb,apbcout,bc2,amb,ambcout,ac2,bma,bmacout)
begin

if m='0' then
	case (s) is
		when "00" => r<= not(a);
		when "10" => r<= a and b;
		when "01" => r<= a or b;
		when "11" => r<= a xor b;
		when others => r <= "----";
	end case;
elsif m='1' then
	if (s)="00" then
		r<=apb;
		Cout<=apbcout;
	elsif (s)="10" then
		r<=amb;
		Cout<=ambcout;
	elsif (s)="01" then
		r<=bma;
		Cout<=bmacout;
	elsif (s)="11" then
		r<=bc2;
		Cout<='1';
	else
		r<="----";
		Cout<='-';
	end if;
end if;
end process;

end bhv;